package com.ophiux.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

public class ImgUtil {
	private static Logger logger = LoggerFactory.getLogger(ImgUtil.class);

	// private static String LOCAL_FILE_PATH = "F:/housePropertySales/uploadImg/";
	public static final String LOCAL_FILE_PATH = PropertyUtil.getResValue("IMG_UPLOAD_URL");

	public static final String LOCAL_FILE_PATH_REALESTATE = LOCAL_FILE_PATH + "img/";

	static {
		makeSureFolderExist(LOCAL_FILE_PATH_REALESTATE);
	}

	private static final int MIN_SIZE = 400;
	private static final int MAX_SIZE = 1600;

	/**
	 * 
	 * Description: 确定文件存在 不存在就创建 <br>
	 * 创 建 人: sunrise 创建日期:2018年9月11日 下午10:27:04
	 */
	private static boolean makeSureFolderExist(String path) {
		boolean exist = true;
		File File = new File(path);
		if (!File.exists()) {
			logger.info("创建文件夹：{}", path);
			exist = File.mkdirs();
			logger.info("创建文件夹：{} {}", path, exist);
		}
		return exist;
	}

	private static boolean zipImg(String imgsrc) {
		boolean sucess = true;
		String imgdistmin;
		String imgdistmax;

		if (imgsrc != null && imgsrc.lastIndexOf(".") > 0) {

			imgdistmin = getImg(imgsrc, 0);
			imgdistmax = getImg(imgsrc, 1);

			ZipImgUtil.reduceImg(imgsrc, imgdistmin, MIN_SIZE, MIN_SIZE, null);
			ZipImgUtil.reduceImg(imgsrc, imgdistmax, MAX_SIZE, MAX_SIZE, null);
		}
		return sucess;
	}

	private static String getImg(String imgsrc, int type) {
		int index = imgsrc.lastIndexOf(".");
		String tag = imgsrc.substring(index, imgsrc.length());
		String temp = imgsrc.substring(0, index);
		switch (type) {
		case 0:
			return temp + "_min" + tag;
		case 1:
			return temp + "_max" + tag;

		default:
			return imgsrc;

		}
	}

	/**
	 *
	 * Description:保存文件 <br>
	 * 创 建 人: xgy 创建日期:2018年9月11日 下午1:08:24
	 * 
	 * @param file
	 * @param bid
	 *            id
	 * @return
	 * @throws Exception
	 */
	public static String saveMultipartFileOfGoods(MultipartFile file, String bid) throws Exception {

		String targetPath = bid + "/" + DateUtil.getCurrentDate("yyyyMMdd") + "/";

		if (!makeSureFolderExist(LOCAL_FILE_PATH_REALESTATE + targetPath)) {
			logger.error("文件夹：{} 创建失败 ,存文件失败", targetPath);
			return null;

		}

		if (file == null) {
			throw new Exception("存文件失败：文件为空");
		}
		if (file.getSize() > 10000000) {
			throw new Exception("存文件失败：文件大小不能超过10M");
		}
		String path = null;
		String filename = file.getOriginalFilename();

		filename = DateUtil.getCurDateRandom() + "_" + filename;
		path = targetPath + filename;
		if (file.getSize() > 0) {
			try {
				SaveFileFromInputStream(file.getInputStream(), LOCAL_FILE_PATH_REALESTATE + targetPath, filename);
				zipImg(LOCAL_FILE_PATH_REALESTATE + targetPath + filename);
				// path = "D:/"+filename;
			} catch (IOException e) {
				System.out.println(e.getMessage());
				return null;
			}
		}

		return path;

	}

	/**
	 *
	 * Description:保存楼盘相册 <br>
	 * 创 建 人: xgy 创建日期:2018年9月11日 下午1:08:24
	 * 
	 * @param file
	 * @param bid
	 *            id
	 * @return
	 * @throws Exception
	 */
	public static String saveMultipartFileOfRealestate(MultipartFile file, String bid, String ID) throws Exception {
		// bid 楼盘ID+相册ID
		String targetPath = LOCAL_FILE_PATH_REALESTATE + bid + "/";
		if (!makeSureFolderExist(targetPath)) {
			logger.error("文件夹：{} 创建失败 ,存文件失败", targetPath);
			return null;

		}

		if (file == null) {
			throw new Exception("存文件失败：文件为空");
		}
		if (file.getSize() > 10000000) {
			throw new Exception("存文件失败：文件大小不能超过10M");
		}
		String path = null;
		String filename = file.getOriginalFilename();

		// filename = DateUtil.getNowTimeYYYYMMDDHHmmss()+"_"+filename;
		if (file.getSize() > 0) {
			try {
				filename = ID + "." + filename.split("\\.")[1];
				path = targetPath + filename;
				SaveFileFromInputStream(file.getInputStream(), targetPath, filename);
				zipImg(targetPath + filename);
				// path = "D:/"+filename;
			} catch (IOException e) {
				System.out.println(e.getMessage());
				return null;
			}
		}

		return filename;

	}

	/**
	 * 
	 * Description:InputStream存文件 <br>
	 * 创 建 人: xgy 创建日期:2018年9月11日 下午1:08:38
	 * 
	 * @param stream
	 * @param path
	 * @param filename
	 * @throws IOException
	 */
	public static void SaveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {
		FileOutputStream fs = new FileOutputStream(path + "/" + filename);
		byte[] buffer = new byte[1024 * 1024];
		int bytesum = 0;
		int byteread = 0;
		while ((byteread = stream.read(buffer)) != -1) {
			bytesum += byteread;
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		fs.close();
		stream.close();
	}

	public static boolean deleteRealestateImg(String imgPath, String picMore, String picType) {
		imgPath = LOCAL_FILE_PATH_REALESTATE + imgPath;
		boolean flag = true;
		try {
			if (StringUtils.isEmpty(picMore) || StringUtils.isEmpty(picType)) {
				File file = new File(imgPath);
				deleteAll(file);
			} else {
				picType = "." + picType;
				String path = imgPath + picMore + picType;
				for (int i = 1; i <= 3; i++) {
					if (i == 2) {
						path = imgPath + picMore + "_min" + picType;
					} else if (i == 3) {
						path = imgPath + picMore + "_max" + picType;
					}
					File file = new File(path);
					// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
					deleteAll(file);
				}
			}
		} catch (Exception e) {
			logger.error("删除文件失败>>>" + imgPath + picMore + picType, e.getMessage());
			flag = false;
		}
		return flag;
	}

	public static void deleteAll(File file) {

		if (file.isFile() || file.list().length == 0) {
			file.delete();
		} else {
			for (File f : file.listFiles()) {
				deleteAll(f); // 递归删除每一个文件
			}
			file.delete(); // 删除文件夹
		}
	}

	public static void main(String[] args) throws IOException {

		// zipImg("d://zip.jpg");

	}

}
